<?php


namespace app\api\controller;

use app\api\model\HealthClassifyModel;
use app\api\model\HealthItemModel;
use app\api\model\HealthKindModel;
use app\api\model\HealthTopicModel;
use app\api\model\UserAdminBMessageModel;
use app\api\model\UserAdminMessage;
use app\api\validate\health\Health;
use app\common\controller\Api;
use app\common\library\Upload;
use think\Db;
use app\common\exception\UploadException;

class HealthClassify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function classify()
    {
        $list = HealthClassifyModel::where(['pid' => 0, 'is_show' => 1])->order('sort desc')->select();

        $this->success('请求成功', $list);
    }


    /**
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \app\common\exception\UploadException
     */
    public function data_import()
    {
        $class_id = input('post.class_id', 2);
        $user_id = input('post.user_id');
        $file = $this->request->file('file');


        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        vendor('PHPExcel.PHPExcel');
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel = new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if ($attachment->imagetype == 'xls') {
            Vendor('PHPExcel.PHPExcel.Reader.Excel5');
            $PHPReader = new \PHPExcel_Reader_Excel5();
        } else if ($attachment->imagetype == 'xlsx') {
            Vendor('PHPExcel.PHPExcel.Reader.Excel2007');
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        } else {
            $this->error('请上传正确的文件');
        }


        //载入文件
        $PHPExcel = $PHPReader->load('.' . $attachment->url);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentNum = $PHPExcel->getSheetCount();

        $currentName = $PHPExcel->getSheetNames();

        $list = [];
        for ($i = 0; $i < $currentNum; $i++) {

            $currentSheet = $PHPExcel->getSheet($i);
            //获取总列数
            $allColumn = $currentSheet->getHighestColumn();
            //获取总行数
            $allRow = $currentSheet->getHighestRow();
            //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
                //从哪列开始，A表示第一列
                for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                    //数据坐标
                    $address = $currentColumn . $currentRow;
                    //读取到的数据，保存到数组$data中
                    $cell = $currentSheet->getCell($address)->getValue();

                    if ($cell instanceof PHPExcel_RichText) {
                        $cell = $cell->__toString();
                    }
                    $data[$currentRow - 1][$currentColumn] = $cell;
//                      print_r($cell);
//                      print_r($data);
                }

            }
            $list[] = $data;
            unset($data);
        }

        $fileName = $attachment->filename;
        $fileName_arr = explode('.', $fileName);
        $res = [];
        Db::startTrans();

        try {
            $topicModel = new HealthTopicModel();
            $res[] = $topicModel->save(['name' => $fileName_arr[0], 'class_id' => $class_id, 'user_id' => $user_id]);
            $topic_id = $topicModel->getLastInsID();
            $kindModel = new HealthKindModel();
            $itemModel = new HealthItemModel();
            foreach ($list as $num => $val) {
                foreach ($val as $key => $item) {
                    if ($key == 0) {
                        $n = 0;
                        $n_arr = [];
                        foreach ($item as $k => $v) {
                            //类型
                            $kindData = [
                                'class_id' => $class_id,
                                'topic_id' => $topic_id,
                                'sheet' => $num,
                                'remark' => $currentName[$num],
                                'attr_name' => $v,
                                'sort' => $n,
                            ];
                            $n++;
                            $kindModel->data($kindData);
                            $res[] = $kindModel->isUpdate(false)->save();
                            $n_arr[] = $kindModel->getLastInsID();
                        }

                    } else {
                        $n = 0;
                        foreach ($item as $k => $v) {
                            //类型
                            $kindData = [
                                'kind_id' => $n_arr[$n],
                                'user_id' => $user_id,
                                'attr_value' => $v,
                                'sort' => $n,
                            ];
                            $n++;
                            $itemModel->data($kindData);
                            $res[] = $itemModel->isUpdate(false)->save();
                        }
                    }
                }
            }

            if (check_arr($res) == false) {
                // 回滚事务
                Db::rollback();
            } else {
                // 提交事务
                Db::commit();
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('导入失败');
        }
        $this->success('导入成功');

    }


    /**
     * 健康主题列表
     * @throws \think\exception\DbException
     */
    public function getTopicList()
    {
        $class_id = input('post.class_id');

        $user_id = input('post.user_id');

        $list = HealthTopicModel::all(['class_id' => $class_id, 'is_show' => 1, 'user_id' => $user_id]);

        $this->success('请求成功', $list);

    }

    /**
     * 获取导入数据
     * @throws \think\exception\DbException
     */
    public function getKindItem()
    {
        $topic_id = input('post.topic_id');

        $sheet = input('post.sheet');

        $title = HealthKindModel::all(['topic_id' => $topic_id, 'sheet' => $sheet]);

        $list = [];
        foreach ($title as $val) {
            $data['title'] = $val;
            $content = HealthItemModel::all(['kind_id' => $val['id']]);
            $data['content'] = $content;
            $list[] = $data;
        }

        $info = [];
        $title = [];
        $content = [];

//        var_dump($list);die;
        foreach ($list as $key => $val) {
            $title[] = $val['title'];
            $n = count($val['content']);
            for ($i = 0; $i < $n; $i++) {
                $info['content'][$key][] = $val['content'][$i];
            }

//            foreach ($list as $k => $v){
//                $info['content'][$key][] = $list[$k]['content'][$key];
//            }
        }

        $num = count($list[0]['content']);
        for ($i = 0; $i < $num; $i++) {

            foreach ($list as $key => $val) {
                $content[$i][] = $val['content'][$i];
            }

        }
//        $this->success('请求成功',$content);
//var_dump($content);die;


        $info = [
            'title' => $title,
            'content' => $content
        ];
//        $this->success('请求成功',$info);

        $this->success('请求成功', $info);

    }

    /*
     * 获取当前sheet属性列表
     */
    public function itemList()
    {
        $topic_id = input('post.topic_id');

        $sheet = input('post.sheet');

        $kind_id = HealthKindModel::get(['topic_id' => $topic_id, 'sheet' => $sheet, 'sort' => 1]);

        $itemList = HealthItemModel::all(['kind_id' => $kind_id['id']]);

        $this->success('请求成功', $itemList);
    }

    /*
     * 报告文件列表
     */
    public function fileList()
    {
        $class_id = input('post.class_id');

        $user_id = input('post.user_id');

        $file_list = HealthTopicModel::all(['class_id' => $class_id, 'user_id' => $user_id, 'is_show' => 1]);

        $this->success('请求成功', $file_list);
    }

    /*
     * 获取单次导入数据
     */
    public function getOneTopic()
    {
        $id = input('post.id');

        $info = HealthTopicModel::all(['id' => ['in', $id]]);

        $this->success('请求成功', $info);
    }

    /*
     * 报告对比分析
     */
    public function healthDetail()
    {
        $topic_str = input('post.topic');
//        $topic_str = '4,5,6';
        $kind_str = input('post.kind');
//        $kind_str = '2,6,14,18';
        $kind_arr = explode(',', $kind_str);
        $file_list = HealthTopicModel::all(['id' => ['in', $topic_str], 'is_show' => 1]);

//        log_print($file_list);
        $list = [];
        foreach ($file_list as $val) {
            $data = [];
            $data['file'] = $val['name'];

            foreach ($kind_arr as $item) {
                $item_item = Db("health_item")->where('id', $item)->value('attr_value');
                $kind_id = Db("health_item")->where('id', ($item + 1))->value("kind_id");
                $kind_name = Db("health_kind")->where("id", $kind_id)->value('remark');
//                log_print($item_item, $kind_name);

                $kind_id = Db("health_kind")->where([
                    'topic_id' => $val['id'],
                    'remark' => $kind_name,
                    'sort' => 1,
                ])->value('id');
//                log_print($kind_id);
                $item_id = Db("health_item")->where([
                    'kind_id' => $kind_id,
                    'attr_value' => $item_item,
                ])->value('id');
//                log_print($item_id);

                $itemInfo = HealthItemModel::get($item_id + 1);
                $data['list'][] = $itemInfo;

//                log_print($item);
//                $itemInfo = HealthItemModel::get($item + 1);
//                $data['list'][] = $itemInfo;
            }
            $list[] = $data;
        }

        $this->success('请求成功', $list);

    }


    /*
     * 导出数据到用户报表
     */
    public function exportToUser()
    {
        $data = input('post.');
        $validate = new Health;

        if (!$validate->scene('export')->check($data)) {

            $this->error($validate->getError());

        } else {
            $data['item'] = html_entity_decode($data['item']);
            $data['kind'] = html_entity_decode($data['kind']);

//            if(!empty($data['item'])){
////                $item = explode(',',$data['item']);
//
//                $data['item'] = json_decode($data['item']);
//                $item_arr = [];
//                foreach ($data['item'] as $val){
//                    $item_arr[] = HealthItemModel::where(['id'=>$val])->value('attr_value');
//                }
//            }
//            $data['item'] = json_encode($item_arr);
            $model = new UserAdminMessage();
            $model->allowField(true)->save($data);

            $this->success('导出成功');
        }


    }

    /*
     * 导出对比分析数据到用户报表
     */
    public function exportDToUser()
    {
        $data = input('post.');
        $validate = new Health;
        if (!$validate->scene('d_export')->check($data)) {

            $this->error($validate->getError());

        } else {

            $data['item'] = json_encode($data['item']);
            $data['kind'] = json_encode($data['kind']);

            $model = new UserAdminBMessageModel();
            $model->allowField(true)->save($data);

            $this->success('导出成功');
        }

    }

    /*
     * 修改导入数据
     */
    public function editItem()
    {
        $id = input('post.id');

        $attr_value = input('post.item');
        if (!$id) {
            $this->error('id必传');
        }
        $model = HealthItemModel::get($id);

        if (!$model) {
            $this->error('当前数据不存在');
        }
        $model->attr_value = $attr_value;
        $model->save();

        $this->success('修改成功');

    }

}